package com.example.springbootdemo.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis相关配置类
 *
 * @author wuzhen on 2020/11/18
 */
@Configuration
public class RedisConfig {

    @Bean("redisTemplate")
    //不指定id的话，Bean的id就是方法名
    public RedisTemplate<String, Object> initRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        //String的序列化器
        RedisSerializer<String> redisKeySerializer = new StringRedisSerializer();
        //使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        RedisSerializer<Object> redisValueSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        //ObjectMapper 指定在转成json的时候的一些转换规则
        ObjectMapper mapper = new ObjectMapper();
        //所有的访问器都可以接收，所有的访问控制符都可以接收
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        //  mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        // mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL);
        //设置时间格式是localdatetime,这样就不会在redis中出现T的时间
        mapper.registerModule(new Jdk8Module()).registerModule(new JavaTimeModule()).registerModule(new ParameterNamesModule());
        //把自定义objectMapper设置到jackson2JsonRedisSerializer中（可以不设置，使用默认规则）
        ((Jackson2JsonRedisSerializer<Object>) redisValueSerializer).setObjectMapper(mapper);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置String的序列化方式
        redisTemplate.setValueSerializer(redisValueSerializer);
        redisTemplate.setKeySerializer(redisKeySerializer);
        //设置Hash的序列化方式
        redisTemplate.setHashKeySerializer(redisKeySerializer);
        redisTemplate.setHashValueSerializer(redisValueSerializer);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}
